package master;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * 全排列2
 *
 * @author chenyw
 * @date 2022/7/25 15:27
 */
public class M47permuteUnique {

    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        int n = nums.length;
        int[] visited = new int[n];
        List<Integer> list = new ArrayList<>();
        Arrays.sort(nums);
        dfs(nums, list, visited, 0);
        return res;
    }

    private void dfs(int[] nums, List<Integer> list, int[] visited, int index) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            //eg: 211131  中间连续3个1
            //visited[i - 1] == 0 只会执行最后一个1开始的重复集合
            //visited[i - 1] == 1 只会执行第一个1开始的重复集合
            if (i > 0 && nums[i-1] == nums[i] && visited[i - 1] == 0) {
                continue;
            }
            if (visited[i] == 1) {
                continue;
            }
            visited[i] = 1;
            list.add(nums[i]);
            dfs(nums, list, visited, i);
            visited[i] = 0;
            list.remove(list.size() - 1);
        }
    }
}
